package com.migraine.controller;

import com.alibaba.fastjson.JSONObject;
import com.migraine.model.Message;
import com.migraine.model.Users;
import com.migraine.service.MessageService;
import com.migraine.service.RelationshipService;
import com.migraine.service.UsersService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;


import java.util.*;
import java.util.concurrent.Semaphore;

@Controller
@ResponseBody
@RequestMapping("/personalPage")
public class PersonalPageController {

    @Autowired
    private RelationshipService relationshipService;

    @Autowired
    private MessageService messageService;

    @Autowired
    private UsersService usersService;

    // 日志工具
    private static final Logger logger = LoggerFactory.getLogger(PersonalPageController.class);

    private Random rand = new Random();

    Semaphore changeinfoSep = new Semaphore(1);
    Semaphore deleteFriSep = new Semaphore(1);
    Semaphore sendMsgSep = new Semaphore(1);

    @GetMapping("/getFriends")
    public String getFriends(@RequestParam String uid) {
        List<Users> usersList = relationshipService.getFriends(uid);
        JSONObject json = new JSONObject();
        json.put("friendsList", usersList);
        return json.toJSONString();
    }

    /**
     * 修改个人信息
     *
     * @param map
     * @return
     */
    @PostMapping("/changeinfo")
    public String changeinfo(@RequestBody Map<String, String> map) {
        String name = map.get("name");
        String photo = map.get("photo");
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        String uids = (String) session.getAttribute("uid");
        int uid = Integer.parseInt(uids);
        Users user = usersService.getUsers(uid);
        String username = user.getUsername();

        Users user2 = usersService.getUsers(name);

        JSONObject json = new JSONObject();
        if (user2 != null) {
            if (!uids.equals(user2.getUid())) {
                // 用户名重复，不能修改 返回er值为1
                json.put("er", "1");
                return json.toJSONString();
            } else {
                try {
                    changeinfoSep.acquire(1);
                    if (!name.equals("")) {
                        usersService.updateNameByName(username, name);
                    }
                    if (!photo.equals("")) {
                        usersService.updateImgById(uid, photo);
                    }
                    json.put("er", "0");

                } catch (InterruptedException e) {
                    logger.info(e.toString());
                    Thread.currentThread().interrupt();
                } finally {
                    changeinfoSep.release(1);
                }

            }
        } else {
            try {
                changeinfoSep.acquire(1);
                if (!name.equals("")) {
                    usersService.updateNameByName(username, name);
                }
                if (!photo.equals("")) {
                    usersService.updateImgById(uid, photo);
                }
                json.put("er", "0");

            } catch (InterruptedException e) {
                logger.info(e.toString());
                Thread.currentThread().interrupt();
            } finally {
                changeinfoSep.release(1);
            }
        }
        return json.toJSONString();
    }

    /**
     * 删除好友功能
     *
     * @param uid
     * @return
     */
    @GetMapping("/deleteFriend")
    public String deleteFriend(@RequestParam String uid) {
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        String userid = (String) session.getAttribute("uid");
        boolean ans = false;
        int availablePermits = deleteFriSep.availablePermits();
        if (availablePermits > 0) {
            try {
                deleteFriSep.acquire(1);
                ans = relationshipService.deleteRelationship(userid, uid);
                ans = relationshipService.deleteRelationship(uid, userid);
            } catch (InterruptedException e) {
                logger.error("错误：", e);
                Thread.currentThread().interrupt();
            } finally {
                deleteFriSep.release(1);
            }
        }
        JSONObject json = new JSONObject();
        json.put("ans", ans);
        return json.toJSONString();
    }

    /**
     * 发送留言
     *
     * @param map
     * @return
     */
    @PostMapping("/sendMessage")
    public String sendMessage(@RequestBody Map<String, String> map) {
        String create = map.get("createtime");
        Date date = new Date(Long.parseLong(create));
        String senderid = map.get("senderid");
        String receiverid = map.get("receiverid");
        String msginfo = map.get("messageinfo");

        int msgid = rand.nextInt();
        while (messageService.selectMessageById(msgid) != null || msgid < 10) {
            msgid = rand.nextInt();
        }
        boolean ans = false;
        int availablePermits = sendMsgSep.availablePermits();
        if (availablePermits > 0) {
            try {
                sendMsgSep.acquire(1);
                ans = messageService.insertMessage(msgid, senderid, receiverid, msginfo, date);
            } catch (InterruptedException e) {
                logger.error("错误：", e);
                Thread.currentThread().interrupt();
            } finally {
                sendMsgSep.release(1);
            }
        }
        JSONObject json = new JSONObject();
        json.put("ans", ans);
        json.put("msgid", msgid);
        return json.toJSONString();
    }


    /**
     * 获得留言板，返回两个数组 一个是留言数组 另一个是留言者数组，两者顺序一致
     *
     * @param uid
     * @return
     */
    @GetMapping("/getMessageBoard")
    public String getMessageBoard(@RequestParam String uid) {
        List<Message> msglist = messageService.getMessageById(uid);
        List<Users> userlist = new ArrayList<>();
        for (Message i : msglist) {
            int senderid = Integer.parseInt(i.getSender());
            userlist.add(usersService.getUsers(senderid));
        }
        JSONObject json = new JSONObject();
        json.put("msglist", msglist);
        json.put("senderlist", userlist);
        return json.toJSONString();
    }
}
